package com.example.myapplication.acticity;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import com.example.myapplication.MyApp;
import com.example.myapplication.R;
import com.example.myapplication.TestBena;
import com.example.myapplication.ToastUtil;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;


public class HomeFragment extends Fragment {
    private AppCompatTextView mainTextView;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        mainTextView = view.findViewById(R.id.mainTextView);
        mainTextView.setText("这是通过代码改的");

        mainTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LiveEventBus.get("position").post(4);
                //从SP读取数据
                String json = MyApp.get().getSharedPreferences().getString("test", "");
                try {
                    JSONArray jsonArray = new JSONArray(json);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        TestBena testBean = new Gson().fromJson(jsonArray.getString(i), TestBena.class);
                        Log.d("TAGS", testBean.getName());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ToastUtil.show(getContext(), MyApp.get().getSharedPreferences().getString("test", ""));
            }
        });

        //接收事件总线消息
        LiveEventBus.get("test", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                mainTextView.setText(s);
            }
        });
        return view;
    }
}
